import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/common/widget/underline_text_field.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_update_pwd_notifier.dart';
import 'package:casdon/modules/login/application/notifier/regist_account_notifier.dart';
import 'package:casdon/modules/login/domain/states/regist_account_state.dart';
import 'package:casdon/modules/login/domain/states/update_pwd_state.dart';
import 'package:casdon/modules/login/domain/validators/password_validator.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

@RoutePage()
class SetNewPwdScreen extends ConsumerStatefulWidget {
  final int gapSize = 24;
  final String? title;

  const SetNewPwdScreen({super.key, this.title});

  @override
  ConsumerState<SetNewPwdScreen> createState() => _SetNewPwdScreenState();
}

class _SetNewPwdScreenState extends ConsumerState<SetNewPwdScreen> {
  final pwdcontroller_1 = TextEditingController();
  final pwdcontroller_2 = TextEditingController();
  late final ProviderSubscription<UpdatePwdState> _forgetPwdSubscription;
  late final ProviderSubscription<RegistAccountState> _registSetPwdSubscription;
  @override
  void initState() {
    super.initState();
    _setupListeners();
  }

  void _setupListeners() {
    _forgetPwdSubscription = ref.listenManual<UpdatePwdState>(
      loginModifyPwdNotifierProvider,
      (pri, next) => _handleUpdatePwdState(pri, next),
    );

    _registSetPwdSubscription = ref.listenManual<RegistAccountState>(
      registerAccountProvider,
      (pri, next) => _handleRegistSetPwdState(pri, next),
    );
  }

  @override
  void dispose() {
    _forgetPwdSubscription.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isLoading = ref.watch(
      loginModifyPwdNotifierProvider.select(
        (s) => s.status == CommonNetStatus.loading,
      ),
    );
    final inputValidator = ref.watch(passwordValidatorProvider);
    final isValid_1 = inputValidator.isValude(pwdcontroller_1.text);
    final isValid_2 = inputValidator.isValude(pwdcontroller_2.text);

    final notifier = ref.watch(loginModifyPwdNotifierProvider.notifier);
    ref.watch(loginModifyPwdNotifierProvider);
    final isEnabled = !isLoading && isValid_1 && isValid_2;

    return Scaffold(
      appBar: CommonAppBar(title: ""),
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        child: KeyboardAvoider(
          duration: const Duration(milliseconds: 300),
          autoScroll: true,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: 25.h),
                Text(
                  widget.title ?? "忘记密码",
                  style: context.textTheme.displayLarge!.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                  ),
                ),
                SizedBox(height: 35.h),
                UnderlineTextField(
                  controller: pwdcontroller_1,
                  hintText: "8-20位密码，包含字母和数字",
                  obscureText: true,
                  keyboardType: TextInputType.emailAddress,
                  onChanged: (value) {
                    notifier.updateNewPwd(value);
                  },
                  validator: PasswordValidator().validateWithMessage,
                ),

                SizedBox(height: 12.h),

                UnderlineTextField(
                  controller: pwdcontroller_2,
                  hintText: "再次输入密码",
                  obscureText: true,
                  keyboardType: TextInputType.emailAddress,
                  onChanged: (value) {
                    notifier.updateNewPwd(value);
                  },
                  validator: PasswordValidator().validateWithMessage,
                ),

                SizedBox(height: 38.h),
                PrimaryButton(
                  text: '完成',
                  onPressed: isEnabled
                      ? () {
                          _handleUpdatePassword(context, ref);
                        }
                      : null,
                  isLoading: isLoading,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _handleUpdatePwdState(UpdatePwdState? pri, UpdatePwdState next) async {
    if (!mounted) return;
    final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);

    if (notifier.step == UpdatePwdtep.updatePwd) {
      if (next.status == CommonNetStatus.success) {
        // 退出：
        if (mounted == false) return;
        await ref.read(tuyaLoginProvider.notifier).logOut();
        await ref.read(authStorageProvider.notifier).clear();
        if (mounted == false) return;
        context.router.replaceAll(const [AccountInputRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "发送验证码失败");
      }
    }
  }

  void _handleUpdatePassword(BuildContext context, WidgetRef ref) {
    if (!mounted) return;
    if (pwdcontroller_1.text != pwdcontroller_2.text) {
      ToastUtil.show("两次密码不一致！");
      return;
    }
    if (widget.title == null) {
      final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);
      notifier.updatePwd();
    } else {
      final notifier = ref.read(registerAccountProvider.notifier);
      notifier.updatePassword(pwdcontroller_1.text);
      notifier.register();
    }
  }

  void _handleRegistSetPwdState(
    RegistAccountState? pri,
    RegistAccountState? next,
  ) async {
    final notifier = ref.read(registerAccountProvider.notifier);
    if (notifier.step == RegistAccountStep.register) {
      if (next!.status == CommonNetStatus.success) {
        if (mounted == false) return;
        
         context.router.replaceAll(const [AccountInputRoute()]);
      } else if (next.status == CommonNetStatus.failure) {
        ToastUtil.show(next.message ?? "注册失败");
      }
    }
  }
}
